/**
 *
 */
package net.frenopatico.citadels.controller.interceptors;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

/**
 * @author eduardo.ramirez.ronco@gmail.com
 *
 */
public class TransactionalInterceptor implements MethodInterceptor {

    /**
     * {@inheritDoc}
     */
    public Object invoke( final MethodInvocation invocation ) throws Throwable {
        final Objectify ofy = ObjectifyService.beginTransaction();
        Object result;
        try {
            result = invocation.proceed();

            ofy.getTxn().commit();
        } finally {
            if( ofy.getTxn().isActive() ) {
                ofy.getTxn().rollback();
            }
        }

        return result;
    }

}
